#include "inifilehelper.h"
#include <QSettings>
#include <QTextCodec>
#include <QString>

namespace Settings {
    static QSettings *settings = nullptr;
}

IniFileHelper::IniFileHelper(QObject *parent)
    :QObject (parent)
{
}

IniFileHelper::~IniFileHelper()
{

}

IniFileHelper *IniFileHelper::getInstance()
{
    static IniFileHelper instance;
    return &instance;
}

void IniFileHelper::LoadFile(QString file_path)
{
    Settings::settings = new QSettings(file_path, QSettings::IniFormat);
    // 设置文件编码，配置文件中使用中文时，这是必须的，否则乱码
    Settings::settings->setIniCodec(QTextCodec::codecForName("UTF8"));
}

void IniFileHelper::SetValue(QString section, QString key, QString value)
{
    Settings::settings->beginGroup(section);
    Settings::settings->setValue(key, value);
    Settings::settings->endGroup();
}

void IniFileHelper::SetValue(QString section, QString key, double value)
{
    Settings::settings->beginGroup(section);
    Settings::settings->setValue(key, QString::number(value));
    Settings::settings->endGroup();
}

void IniFileHelper::SetValue(QString section, QString key, int value)
{
    Settings::settings->beginGroup(section);
    Settings::settings->setValue(key, QString::number(value));
    Settings::settings->endGroup();
}

QList<QString> IniFileHelper::GetKeys(QString section)
{
    Settings::settings->beginGroup(section);
    QList<QString> keys = Settings::settings->allKeys();
    Settings::settings->endGroup();
    return  keys;
}

QList<QString> IniFileHelper::GetNames(QString section)
{
    QString newsection= QString::fromUtf8(section.toLatin1()); //重
    Settings::settings->beginGroup(newsection);
    QList<QString> keys = Settings::settings->allKeys();
    QList<QString> Names;
    foreach(QString key, keys)
    {
        Names.append(Settings::settings->value(key).toString());
    }
    Settings::settings->endGroup();
    return  Names;
}

void IniFileHelper::GetValue(QString section, QString key, QString *value)
{
    Settings::settings->beginGroup(section);
    *value = Settings::settings->value(key).toString();
    Settings::settings->endGroup();
}

void IniFileHelper::GetValue(QString section, QString key, int *value)
{
    Settings::settings->beginGroup(section);
    *value = Settings::settings->value(key).toInt();
    Settings::settings->endGroup();
}

void IniFileHelper::GetValue(QString section, QString key, double *value)
{
    Settings::settings->beginGroup(section);
    *value = Settings::settings->value(key).toDouble();
    Settings::settings->endGroup();
}



